package com.github.cakin.shiro.chapter19.web.shiro.filter;

import com.github.cakin.shiro.chapter19.Constants;
import com.github.cakin.shiro.chapter19.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @className: SysUserFilter
 * @description: 用户过滤器
 * @date: 2020/5/26
 * @author: cakin
 */
public class SysUserFilter extends PathMatchingFilter {
    /**
     * 注入用户服务
     */
    @Autowired
    private UserService userService;

    /**
     * 功能描述：将用户信息设置到web属性中
     *
     * @param request     请求
     * @param response    响应
     * @param mappedValue mappedValue
     * @return boolean 过滤链是否继续
     * @author cakin
     * @date 2020/5/26
     */
    @Override
    protected boolean onPreHandle( ServletRequest request, ServletResponse response, Object mappedValue ) {
        // 获得用户信息
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        // 设置用户信息到“user”属性中
        request.setAttribute(Constants.CURRENT_USER, userService.findByUsername(username));
        return true;
    }
}
